<?php
/**
 *
 * GPS 解析
 * @author cosnis
 *
 */
class tls_gpsparse{
	/**
	 *
	 * 通过坐标解析出物理地址信息
	 * @param unknown_type $latitude 维度
	 * @param unknown_type $longitude 经度
	 * @param unknown_type $language 语言
	 */
	public function GetAddress($latitude,$longitude,$language){
		switch ($language){
			case 'zhcn':
				$url="http://maps.google.cn/maps/api/geocode/json?latlng=".$latitude.",".$longitude."&sensor=true";
				break;
			default:
				$url="http://maps.google.com/maps/api/geocode/json?latlng=".$latitude.",".$longitude."&sensor=true";
				break;
		}
		$file = fopen($url,"r");
		while(!feof($file))
		{
			$line .= fgets($file,1024);

		}
		fclose($file);
		$address=json_decode($line);
		return $address->results[0]->formatted_address;
	}

	/**
	 *
	 * 通过GSM基站 信息解析 得到GPS坐标..
	 * @param unknown_type $cellId
	 * @param unknown_type $locationAreaCode
	 * @param unknown_type $mobileCountryCode
	 * @param unknown_type $mobileNetworkCode
	 */
	public function  GsmToGps($cellId,$locationAreaCode,$mobileCountryCode,$mobileNetworkCode){
		$curlPost = '{"version": "1.1.0" ,"host": "maps.google.com","home_mobile_country_code": '.$mobileCountryCode.',"home_mobile_network_code":'.$mobileNetworkCode.',"address_language": "zh_CN","radio_type": "gsm","request_address": true ,"cell_towers":[{"cell_id":'.$cellId.',"location_area_code":'.$locationAreaCode.',"mobile_country_code":'.$mobileCountryCode.',"mobile_network_code":'.$mobileNetworkCode.',"timing_advance":5555}]}';
		$fp = fsockopen("www.google.com",80,$errno,$errstr,30);
		if(!$fp){
			return array('latitude'=>0,'longitude'=>0);
		}else{
			$out = "POST /loc/json HTTP/1.1\r\n";
			$out .= "Host: www.google.com\r\n";
			$out .= "Content-Type: application/jsonrequest\r\n";
			$out .= "Content-Length: ". strlen($curlPost) ."\r\n";
			$out .= "Connection: Close\r\n\r\n";
			$out .=  $curlPost;
			fwrite($fp, $out);
			do{
				$line = fgets($fp,128);
			}while($line!=="\r\n");
			$data = fread($fp, 8192);
			fclose($fp);
			$arr = json_decode($data,true);
			$latitude = empty($arr["location"]["latitude"])?0.0:$arr["location"]["latitude"];
			$longitude = empty($arr["location"]["longitude"])?0.0:$arr["location"]["longitude"];
			return array('latitude'=>$latitude,'longitude'=>$longitude);
		}
	}

}